package com.turman.coroutionsample.download

import com.turman.coroutionsample.utils.copyTo
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.flowOn
import okhttp3.OkHttpClient
import okhttp3.Request
import java.io.File
import java.io.IOException

object DownloadManager {
    //文件下载，要实现的功能，下载进度条
    //这里通过下载时okhttp的body来读取数据，将body中的数据二进制读取到file文件中，这个过程需要发送进度信息
    //进度的状态：文件读取中-progress，文件读取完成-done，下载和读取异常-error
    fun download(url: String, file: File): Flow<DownloadStatus> {
        return flow {
            val request = Request.Builder().url(url).get().build()
            val response = OkHttpClient.Builder().build().newCall(request).execute()
            if (response.isSuccessful) {
                response.body?.let { body ->
                    val total = body.contentLength()
                    //读取文件
                    file.outputStream().use { output ->
                        val input = body.byteStream()
                        var emittedProcess = 0f
                        input.copyTo(output) { copied ->
                            val progress = (copied * 1.0f) / total
//                            Log.i("buobao","progress:$progress, emittedProcess:$emittedProcess")
                            if (progress - emittedProcess > 0.0001) {
                                emit(DownloadStatus.Progress(progress))
                                emittedProcess = progress
                            }
                        }
                    }
                }
                emit(DownloadStatus.Done(file))
            } else {
                throw IOException(response.toString())
            }
        }.catch {
            file.delete()
            emit(DownloadStatus.Error(it))
        }.flowOn(Dispatchers.IO)
    }

}